//
//  AppDelegate.swift
//  爱汽车
//
//  Created by liujianlong on 2023/8/8.
//

import UIKit
import TCCKit
import SwiftyJSON

enum CONTRYTYPE : Int{
    case china = 0
    case abroad = 1
    case other = 2
}

///新增设备支持模式
enum DeviceMode : Int{
    ///支持高度和气压模式
    case supportHeightPressure = 0;
    ///支持仅气压模式
    case supportPressure = 1;
}
var deviceMode : DeviceMode?
///是否 是 气压记忆模式
var isPressureMode : Bool = true

let APP : AppDelegate = UIApplication.shared.delegate as! AppDelegate
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window : UIWindow?
    var language = ""
    var mcuArray = [MCUModel]()
    var otaArray = [OTAModel]()
    var appModel = AppModel()
    var contry = CONTRYTYPE.abroad
    var log = Logwindow()
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        
        let dict = Bundle.main.infoDictionary!
        let version = dict["CFBundleShortVersionString"] as! NSString
        let build = dict["CFBundleVersion"] as! String
        appModel.version = (version as String) + "." + build
        setupSDK()
        self.window = UIWindow(frame: UIScreen.main.bounds)
        self.window?.rootViewController = QCTabBarViewController()
        self.window?.makeKeyAndVisible()
        addNotify()
        
        let defaults = ["key_diameter":"2.3","dfu_number_of_packets":NSNumber.init(value: 6),"dfu_force_dfu":false] as [String : Any]
        UserDefaults.standard.register(defaults: defaults)
        return true
    }
    
    
}

//MARK: - 键盘相关通知
extension AppDelegate{
    private func addNotify(){
        NotifyTool.add(self, #selector(methodVersion), BLEData.checkFirmwareInfo.ack)
    }
    
    @objc private func methodVersion(_ notify:Notification){
        guard let userinfo = notify.userInfo as? [String:[UInt8]] else{return}
        guard let bytes = userinfo["data"] else{return}
        let str = bytes.map{String(format: "%.2X ", Int($0))}.joined()
        let tag1 = String(format: "%.2X", bytes[0])///索引01
        let length1 = bytes[1...2].map{String(format:"%.2X", $0)}.joined().toDecimal()///数据长度
        let binCode = bytes[3...6].map{String(format:"%.2X", $0)}.joined()///BIN文件的匹配码
        let l_mcu_same = String(format:"%.2X", bytes[7])///单个 MCU 共同特征参数长 度
        let l_mcu_arr = String(format:"%.2X", bytes[8])///单个 MCU-元组长度
        let num_mcu = String(format:"%.2X", bytes[9]).toDecimal()///含 MCU 数目
        
        mcuArray.removeAll()
        var index = 9
        for _ in 0..<num_mcu{
            let mcu = MCUModel()
            let tag = String(format: "%.2X", bytes[index+1])///索引
            let length = bytes[index+2...index+3].map{String(format:"%.2X", $0)}.joined().toDecimal()///数据长度
            let productNum = bytes[index+4...index+5].map{String(format:"%.2X", $0)}.joined()///产品编号
            let num = String(format:"%.2X", bytes[index+6])///MCU 序 号（与下面的识别码，组成4个字节，用于区分用途）
            index += 6
            
            for _ in 0..<(length-3)/6{///单个mcu的元组个数
                let mcu = MCUModel()
                mcu.productNum = productNum
                mcu.tag = tag
                mcu.binCode = binCode
                mcu.code = num+bytes[index+1...index+3].map{String(format:"%.2X", $0)}.joined()///识别码
                mcu.version = "\(bytes[index+4...index+6].map{String(format:"%02X", $0)}.joined().toDecimal())"///版本号
                mcu.versionStr = bytes[index+4...index+6].map{String(format:"%d.", $0)}.joined()///版本号
                mcu.versionStr = mcu.versionStr.count <= 1 ? mcu.versionStr : mcu.versionStr[0...mcu.versionStr.count-2]
                mcuArray.append(mcu)
                index += 6
            }
        }
        checkOTA()
    }
    
    ///固件升级
    func checkOTA(_ showUpdte:Bool=true) {
        if BLE.connectedPeripherals.count <= 0 {
            return
        }
        if mcuArray.count <= 0 {
            CCHud.start(LS("请稍后..."), stopTime: 1.5)
            return
        }
        let list = mcuArray.map{
            return ["identificationCode":$0.code,
                    "broadcastId":"0x"+$0.productNum,
                    "versionCode":$0.version]}
        let param = ["matchCode":mcuArray[0].binCode,
                     "mcuList":list] as [String : Any]
        NetworkTool.request(.checkUpdate(param)) {[weak self] json in
            print("====固件升级\(json)")
            guard let dict = json["data"].dictionary else{return}
            guard let array = dict["firmwareList"]?.array  else{return}
            guard let mcuArray = self?.mcuArray else{return}
            self?.otaArray = array.map{ item  in
                let model = OTAModel.json(item)
                guard let mcu = mcuArray.filter({$0.code.uppercased() == model.code.uppercased()}).first else {return model}
                model.tag = mcu.tag
                return model
            }
            NotifyTool.post(updateVersion)
            if showUpdte == false{return}
            self?.showUpdate()
        }
    }
    
    ///APP升级
    func checkAPPUpdate(){
        let param = ["appVersion":appModel.localVersionCode,
                     "appType":"2"] as [String : Any]
        NetworkTool.request(.checkUpdate(param)) {[weak self] json in
            print("====app升级\(json)")
            guard let dict = json["data"].dictionary else{return}
            guard let appVo = dict["appVo"]  else{return}
            guard let code = appVo["versionCode"].stringValue as? String else{return}
            guard let self = self else{return}
            let version = "\(self.appModel.version)"
            self.appModel = AppModel.json(appVo)
            self.appModel.version = version
            NotifyTool.post(updateVersion)
            if self.currentVC().className == "QCAboutViewController" {return}
            if code.intValue() > self.appModel.localVersionCode{
                self.appModel.forceUpdate ? self.forceUpdate(self.appModel.ota) : self.showAlert(self.appModel.ota)
            }
        }
    }
    
    ///APP强制更新
    private func forceUpdate(_ string:String){
        guard let url = URL(string: string)else{return}
        
        currentVC().alert(LS("注意"),LS("检测到有最新版本，是否前去更新？"),{ [weak self] in
            UIApplication.shared.open(url, options:[:], completionHandler:nil)
            self?.forceUpdate(string)
            
        },{[weak self] in
            UIApplication.shared.open(url, options:[:], completionHandler:nil)
            self?.forceUpdate(string)
        })
    }
    
    ///APP弹出升级提示框
    private func showAlert(_ string:String){
        guard let url = URL(string: string)else{return}
        let time = ((UserDefaults.standard.value(forKey:"AppUpgradeTime") as? String ?? "0") as NSString).intValue
        let stamp = Date().timeIntervalSince1970
        
        if stamp <= Double(time + 86400){
            return
        }
        
        currentVC().alert(LS("注意"),LS("检测到有最新版本，是否前去更新？"),{
            UserDefaults.standard.setValue("\(stamp+86400)", forKey:"AppUpgradeTime")
        },{
            UIApplication.shared.open(url, options:[:], completionHandler:nil)
        })
    }
    
    ///OTA升级框
    private func showUpdate(){
        if self.currentVC().className == "QCUpdateViewController" {return}
        if self.currentVC().className == "QCAboutViewController" {return}
        var content = ""
        for i in 0..<otaArray.count{
            let ota = otaArray[i]
            content += String(format: "\n%d、%@", i+1, ota.content)
        }
        
        if otaArray.count > 0 {
            return
            /* DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
             let vc = QCUpdateViewController()
             vc.titleLbl.text = "有固件更新"
             vc.contentView.text = "更新内容" + content
             vc.block = {[weak self] in
             self?.currentVC().navigationController?.pushViewController(QCAboutViewController(), animated: true)
             }
             self.currentVC().present(vc, animated: false)
             }
             */
        }
    }
}


//MARK: - 设置一些sdk
extension AppDelegate{
    
    func setupSDK(){
        setupPgy()
        setupUMCommon()
    }
    
    ///设置蒲公英SDK
    private func setupPgy(){
        //        ///启动基本SDK
        //        PgyManager.shared().isFeedbackEnabled = false
        //        PgyManager.shared().start(withAppId:PgyAPPKey)
        //        ///启动更新检查SDK
        //        PgyUpdateManager.sharedPgy().start(withAppId: PgyAPPKey)
        //        PgyUpdateManager.sharedPgy().checkUpdate()
    }
    
    private func setupUMCommon(){
        UMConfigure.setLogEnabled(true)
        UMConfigure.initWithAppkey(UMKey, channel: "App Store")
    }
}
